package com.wkbb.basic.controller.manage;

import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageInfo;
import com.wkbb.basic.model.OrgStructureUser;
import com.wkbb.basic.model.Student;
import com.wkbb.basic.service.OrgStructureUserService;
import com.wkbb.basic.service.StudentService;
import com.wkbb.basic.service.UserService;
import com.wkbb.basic.vo.StudentManageEditVo;
import com.wkbb.common.base.BaseController;
import com.wkbb.common.constants.ErrorCode;
import com.wkbb.common.constants.VersionConstant;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.common.dto.basic.FamilyInfoDto;
import com.wkbb.common.dto.basic.StudentInfoDto;
import com.wkbb.common.dto.basic.UserDto;
import com.wkbb.common.utils.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileInputStream;
import java.util.*;

/**
 * @author lizhichao
 * @date 2019/8/9
 * @description
 */
@RestController
@Api(description = "校友管理")
@RequestMapping("/basic/{apiVersion}/alumnus/manage")
@Slf4j
public class AlumnusManageController extends BaseController {

    @Autowired
    private StudentService studentService;
    @Autowired
    private OrgStructureUserService orgStructureUserService;
    @Autowired
    private UserService userService;

    @ApiOperation("新增校友")
    @RequestMapping(value = "/addAlumnus", method = RequestMethod.POST)
    public ResultDTO addAlumnus(
            @ApiParam(value = "接口版本",defaultValue = "v1",required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "组织架构Id",required = true) @RequestParam(name = "structureId",required = false) Long structureId,
            @ApiParam("校友集合") @RequestBody StudentInfoDto studentInfoDto) {
        log.info("***********AlumnusManageController.addAlumnus******apiVersion:{},structureId:{}", apiVersion, structureId);
        UserDto userDto = this.getUserByLogin();
        if (userDto == null) {
            return new ResultDTO(ErrorCode.USER_NOT_EXIST);
        } else if (studentInfoDto == null || studentInfoDto.getId() == null) {
            return new ResultDTO(ErrorCode.PARAM_MISSING);
        }
        try {
            Long orgId = ((JSONArray)userDto.getRoleType()).getJSONObject(0).getLong("orgId");
            return orgStructureUserService.addAlumnus(studentInfoDto,userDto.getName(),structureId,orgId);
        } catch (Exception e) {
            log.error("AlumnusManageController.addAlumnus**增加校友异常", e);
            return new ResultDTO(false);
        }
    }

    @ApiOperation("批量新增校友")
    @RequestMapping(value = "/addAlumnusBatch", method = {RequestMethod.POST})
    public ResultDTO addAlumnusBatch(
            @ApiParam(value = "接口版本",defaultValue = "v1",required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "组织架构Id",required = true) @RequestParam(name = "structureId",required = false) Long structureId,
            @ApiParam("校友集合") @RequestBody List<StudentInfoDto> studentInfoDtoList) {
        log.info("***********AlumnusManageController.addAlumnusBatch******apiVersion:{},structureId:{},studentInfoDtoList:{}",
                apiVersion, structureId,studentInfoDtoList.size());
        UserDto userDto = this.getUserByLogin();
        if (userDto == null) {
            return new ResultDTO(ErrorCode.USER_NOT_EXIST);
        } else if (studentInfoDtoList.size() == 0 || studentInfoDtoList.isEmpty()) {
            return new ResultDTO(ErrorCode.PARAM_MISSING);
        }
        try {
            Long orgId = ((JSONArray)userDto.getRoleType()).getJSONObject(0).getLong("orgId");
            return orgStructureUserService.addAlumnusBatch(studentInfoDtoList,userDto.getName(),structureId,orgId);
        } catch (Exception e) {
            log.error("AlumnusManageController.addAlumnusBatch**批量增加校友异常", e);
            return new ResultDTO(false);
        }
    }

    @ApiOperation("批量导入校友")
    @RequestMapping(value = {"/importAlumnusBatch"}, method = {RequestMethod.POST})
    public ResultDTO importAlumnusBatch(
            @ApiParam(value = "接口版本",defaultValue = "v1",required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "文件",required = true) @RequestParam(name = "file",required = false) MultipartFile multipartFile) {
        log.info("***********AlumnusManageController.importAlumnusBatch******apiVersion:{},structureId:{}",apiVersion);

        UserDto userDto = this.getUserByLogin();
        if (userDto == null || multipartFile == null) {
            return new ResultDTO(ErrorCode.USER_NOT_EXIST);
        } else if (multipartFile == null) {
            return new ResultDTO(ErrorCode.PARAM_MISSING);
        } else {
            try {
                Long orgId = ((JSONArray)userDto.getRoleType()).getJSONObject(0).getLong("orgId");
                File file = new File(multipartFile.getOriginalFilename());
                List<Object[]> objects = ExcelUtil.importExcel(new FileInputStream(file));
                //校友信息数据集合
                List<Student> students = new ArrayList();
                //组织成员数据信息集合
                List<OrgStructureUser> orgStructureUserList = new ArrayList();
                //组装老师数据
                for(Object[] obj : objects ){
                    Student student = new Student();
                    student.setStudentNo(obj[0].toString());//学号
                    student.setCreateBy(userDto.getName());
                    student.setUpdateBy(userDto.getName());
                    student.setOrgId(orgId);
                    students.add(student);
                    OrgStructureUser orgStructureUser = new OrgStructureUser();
                    //todo 根据学号查询userId和structureId
//                  orgStructureUser.setUserId(employee.getUserId());
//                  orgStructureUser.setStructureId(structureId);
                    orgStructureUser.setOrgId(orgId);
                    orgStructureUserList.add(orgStructureUser);
                }

                return this.orgStructureUserService.importAlumnusBatch(students,orgStructureUserList);
            } catch (Exception e) {
                log.error("***********AlumnusManageController.importAlumnusBatch******移动到学生异常批量导入校友异常", e);
                return new ResultDTO(false);
            }
        }
    }

    @ApiOperation("移动到学生")
    @RequestMapping(value = "/alumnusToStudent", method = {RequestMethod.PUT})
    public ResultDTO alumnusToStudent(
            @ApiParam(value = "接口版本",defaultValue = "v1",required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam("校友集合") @RequestBody StudentInfoDto studentInfoDto) {
        log.info("***********AlumnusManageController.alumnusToStudent******apiVersion:{},studentInfoDto:{}",
                apiVersion, studentInfoDto);
        UserDto userDto = this.getUserByLogin();
        if (userDto == null) {
            return new ResultDTO(ErrorCode.USER_NOT_EXIST);
        } else if (studentInfoDto == null) {
            return new ResultDTO(ErrorCode.PARAM_MISSING);
        }
        try {
            return orgStructureUserService.alumnusToStudent(studentInfoDto, userDto.getName());
        }catch (Exception e) {
            log.error("***********AlumnusManageController.alumnusToStudent******移动到学生异常", e);
            return new ResultDTO(false);
        }
    }

    @ApiOperation("批量移动到学生")
    @RequestMapping(value = "/alumnusToStudentBatch", method = RequestMethod.PUT)
    public ResultDTO alumnusToStudentBatch(
            @ApiParam(value = "接口版本",defaultValue = "v1",required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam("校友集合") @RequestBody List<StudentInfoDto> studentInfoDtoList) {
        log.info("***********AlumnusManageController.alumnusToStudent******apiVersion:{},studentInfoDtoList:{}",
                apiVersion, studentInfoDtoList.size());
        UserDto userDto = this.getUserByLogin();
        if (userDto == null) {
            return new ResultDTO(ErrorCode.USER_NOT_EXIST);
        } else if (studentInfoDtoList == null || studentInfoDtoList.isEmpty()) {
            return new ResultDTO(ErrorCode.PARAM_MISSING);
        }
        try {
            return orgStructureUserService.alumnusToStudentBatch(studentInfoDtoList,userDto.getName());
        }catch (Exception e) {
            log.error("***********AlumnusManageController.alumnusToStudentBatch******批量移动到学生异常", e);
            return new ResultDTO(false);
        }
    }

    @ApiOperation("批量删除校友")
    @RequestMapping(value = "/deleteAlumnusBatch", method = RequestMethod.DELETE)
    public ResultDTO deleteAlumnusBatch(
            @ApiParam(value = "接口版本",defaultValue = "v1",required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam("校友集合") @RequestBody List<StudentInfoDto> studentInfoDtos) {
        log.info("***********AlumnusManageController.getAlumnusInfoPage******apiVersion:{},studentInfoDtos:{}",studentInfoDtos);
        UserDto userDto = this.getUserByLogin();
        if (userDto == null) {
            return new ResultDTO(ErrorCode.USER_NOT_EXIST);
        }  else if (studentInfoDtos == null || studentInfoDtos.isEmpty()) {
            return new ResultDTO(ErrorCode.PARAM_MISSING);
        }
        try {
            List<OrgStructureUser> orgStructureUsers = new ArrayList();
            Long orgId = ((JSONArray)userDto.getRoleType()).getJSONObject(0).getLong("orgId");
            Iterator iterator = studentInfoDtos.iterator();

            while(iterator.hasNext()) {
                StudentInfoDto studentInfoDto = (StudentInfoDto)iterator.next();
                if (studentInfoDto.getStructureUserId() == null || studentInfoDto.getId() == null) {
                    return new ResultDTO(ErrorCode.PARAM_MISSING);
                }
                OrgStructureUser orgStructureUser = new OrgStructureUser();
                orgStructureUser.setId(studentInfoDto.getStructureUserId());
                orgStructureUser.setOrgId(orgId);
                orgStructureUsers.add(orgStructureUser);
            }

            this.orgStructureUserService.deleteBatch(orgStructureUsers);
            return new ResultDTO(true);
        } catch (Exception e) {
            log.error("***********AlumnusManageController.deleteAlumnusBatch******批量删除校友异常", e);
            return new ResultDTO(false);
        }
    }

    @ApiOperation("根据姓名、学号、手机号、组织机构号等查询校友分页列表")
    @RequestMapping(value = "getAlumnusInfoPage", method = RequestMethod.GET)
    public ResultDTO<PageInfo<StudentInfoDto>> getAlumnusInfoPage(
            @ApiParam(value = "接口版本",required = true,defaultValue = "v1") @PathVariable(value = "apiVersion",required = true) String apiVersion,
            @ApiParam(value = "姓名",required = false) @RequestParam(name = "name",required = false) String name,
            @ApiParam(value = "手机号",required = false) @RequestParam(name = "mobile",required = false) String mobile,
            @ApiParam(value = "学号",required = false) @RequestParam(name = "studentNo",required = false) Long studentNo,
            @ApiParam(value = "组织机构号",required = false) @RequestParam(name = "structureId",required = false) Long structureId,
            @ApiParam(value = "页码",required = false,defaultValue = "1") @RequestParam(name = "pageNo",required = false,defaultValue = "1") Integer pageNo,
            @ApiParam(value = "每页条数",required = false,defaultValue = "10") @RequestParam(name = "pageSize",required = false,defaultValue = "10") Integer pageSize) {
        log.info("***********AlumnusManageController.getAlumnusInfoPage******apiVersion:{},name:{},mobile:{},studentNo:{}",
                new Object[]{apiVersion, name, mobile, studentNo});
        UserDto userDto = this.getUserByLogin();
        if (userDto == null) {
            return new ResultDTO(ErrorCode.USER_NOT_EXIST);
        }
        try {
            Long orgId = ((JSONArray)userDto.getRoleType()).getJSONObject(0).getLong("orgId");
            Map<String, Object> params = new HashMap(2);
            if (mobile != null) {
                params.put("mobile", mobile);
            }
            if (name != null) {
                params.put("name", name);
            }
            if (studentNo != null) {
                params.put("studentNo", studentNo);
            }
            if (structureId != null) {
                params.put("structureId", structureId);
            }
            if (orgId != null) {
                params.put("orgId", orgId);
            }
            return new ResultDTO(this.orgStructureUserService.getAlumnusInfoPageList(params, pageNo, pageSize));
        } catch (Exception e) {
            log.error("***********AlumnusManageController.getAlumnusInfoPage******查询校友分页列表异常", e);
            return new ResultDTO(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "修改校友")
    @RequestMapping(value = "/updateAlumnus", method = RequestMethod.PUT)
    public ResultDTO updateAlumnus(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam("校友集合") @RequestBody StudentManageEditVo studentManageEditVo) {
        log.info("***********AlumnusManageController.updateStudent******...apiVersion:{},Student:{}", apiVersion, studentManageEditVo);

        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        StudentInfoDto studentInfoDto = studentManageEditVo.getStudentInfoDto();

        if (studentInfoDto == null || studentInfoDto.getId() == null || studentInfoDto.getId() == 0
                || studentInfoDto.getUserId() == null || studentInfoDto.getUserId() == 0) {
            return new ResultDTO<>(ErrorCode.PARAM_MISSING);
        }

        List<FamilyInfoDto> familyInfoList = studentManageEditVo.getFamilyInfoList();
        if (familyInfoList != null && !familyInfoList.isEmpty()) {
            familyInfoList.forEach(familyInfoDto -> {
                if (familyInfoDto == null){
                    return;
                }
                //TODO 后台暂不支持修改手机
                familyInfoDto.setMobile(null);
            });
        }

        try {
            studentService.update(studentManageEditVo, userDto.getName(),true);
            return new ResultDTO<>(true);
        } catch (Exception e) {
            log.error("***********AlumnusManageController.updateStudent******", e);
            return new ResultDTO<>(false);
        }
    }

}
